package org.JDBC;

// 添加必要的导入语句
import org.junit.Test;
import java.sql.*;

public class TransactionTest {

    private String driverClass = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://127.0.0.1:3306/briup";
    private String user = "root";
    private String password = "1234";

    @Test
    public void transaction() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
//1.加载注册驱动
            Class.forName(driverClass);
//2.获取连接对象
            conn =
                    DriverManager.getConnection(url,user,password);
//设置事务自动提交为false，也就是需要手动提交
            conn.setAutoCommit(false);
//3.获取Statement对象
            String sql = "update t_user set name=? where id = ?";
            pstmt = conn.prepareStatement(sql);
//4.执行SQL语句
            pstmt.setString(1,"lucy");
            pstmt.setInt(2,1);
            int rows = pstmt.executeUpdate();
//手动提交事务
            conn.commit();
//5.处理结果
            System.out.println("运行结果：rows = " + rows);
        } catch (Exception e) {
//出现异常，回滚事务
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
//6.释放资源
            if(pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
